<template>
    <rx-layout>
        <div slot="left" width="200" showButton="true" style="padding: 10px" v-if="!groupId">
            <a-input style="margin-bottom: 8px" :placeholder="i18n('search.dimension','搜索维度')" v-model="searchValue" @change="handleChange"
                     ref="searchInput">
                <a-icon slot="prefix" type="search"/>
                <a-icon v-if="searchValue" slot="suffix" type="close-circle" @click="emitEmpty"/>
            </a-input>

            <rx-vue-tree
                v-model="selectedKeys"
                :tree-data="dimTree"
                :showCheckbox="false"
                @rowClick="handleDimSelectRxVueTree"
                :expandedKeys.sync="expandedKeys"
            >
            </rx-vue-tree>
        </div>
        <div slot="center" style>
            <rx-fit>
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <rx-button alias="osGroupPrivilegeAdd" :butn-icon="'plus'" :butn-type="'primary'"
                                   :show-no-right="true" @click="addPrivilege">{{$ti18('rxList.newBtn','新建')}}
                        </rx-button>
                    </div>
                    <span class="search-btn-box">
                        <span v-if="isShowSearch" class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                            {{$ti18('rxList.leachBtn','过滤')}}
                        </span>
                      </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.groupName','授权组名称')">
                                    <a-input :placeholder="i18n('form.groupName','授权组名称','input')" v-model="queryParam.Q_GROUP_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    v-if="groupId"
                    ref="table"
                    :allowRowSelect="false"
                    :multiSelect="false"
                    :columns="columns"
                    :defaultPageSize="10"
                    :dataSource="dataSource"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :showPage="false"
                    id-field="idx_"
                    @selectChange="onSelectChange"
                >
                     <span slot="containSub" slot-scope="{ text, record }">
                        <a-radio-group  v-model="record.containSub">
                            <a-radio value="YES">{{i18n('isSysMap.yes','是')}}</a-radio>
                            <a-radio value="NO">{{i18n('isSysMap.no','否')}}</a-radio>
                        </a-radio-group>
                    </span>
                    <span slot="action" slot-scope="{ text, record ,index}" class="actionIcons">
                        <span v-if="groupId" @click.stop="save(record,index)">{{$ti18('rxForm.saveBtn','保存')}}</span>
                        <span v-if="record.pkId" @click.stop="assignMenu(record)" :title="i18n('list.assignMenu','授权菜单')">{{i18n('list.assignMenu','授权菜单')}}</span>
                        <span @click.stop="del(record,index)">{{$ti18('rxList.delBtn','删除')}}</span>
                  </span>
                </rx-grid>
                <rx-grid
                    v-else
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="false"
                    :multiSelect="false"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-user/user/org/osGroupPrivilege/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="idx_"
                    @selectChange="onSelectChange"
                >
                     <span slot="containSub" slot-scope="{ text, record }">
                        <a-tag  :color="containSubMap[text].color">
                            <span>{{ containSubMap[text].text }}</span>
                         </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record ,index}" class="actionIcons">
                        <span v-if="record.pkId" @click.stop="assignMenu(record)" :title="i18n('list.assignMenu','授权菜单')">{{i18n('list.assignMenu','授权菜单')}}</span>
                        <span @click.stop="del(record,index)">{{$ti18('rxList.delBtn','删除')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import OsGroupPrivilegeApi from '@/api/user/org/osGroupPrivilege'
import {BaseList, RxFit, RxGrid,Util } from "@lowcode/jpaas-common-lib";
import OsGroupMenuEdit2 from "@/views/modules/user/org/OsGroupMenuEdit2.vue"
import OsGroupGrant from "@/views/modules/user/org/OsGroupGrant.vue"
import OsDimensionApi from "@/api/user/org/osDimension";

export default {
    name: 'OsGroupPrivilegeList',
    mixins: [BaseList],
    components: {
        RxFit
    },
    props:["groupId","appId","groupName","dimId","showSearch"],
    computed:{
        //是否显示过滤，默认显示
        isShowSearch(){
            if(this.showSearch!=null){
                return this.showSearch;
            }
            return  true
        }
    },
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 50,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.i18n('form.groupName','授权组名称'), dataIndex: 'groupName', width: 120},
                {title: this.i18n('form.containSub','包含下级'), dataIndex: 'containSub', width: 120, scopedSlots: {customRender: 'containSub'}},
                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime', sorter: true, sortField: 'CREATE_TIME_', width: 100},
                {title: this.$ti18('rxList.action','操作'), width: 120, dataIndex: 'action', scopedSlots: {customRender: 'action'},size:3}
            ],
            dataSource:[],
            containSubMap: {
                "YES": { color: 'green', text: this.i18n('isSysMap.yes','是') },
                "NO": { color: 'red', text: this.i18n('isSysMap.no','否') },
            },
            selectedKeys: [],
            // 查询参数
            searchValue: "",
            expandedKeys: [],
            autoExpandParent: false,
            originDimTree:[],
            dimTree: [],
        }
    },
    created() {
        this.init();
        this.setParam();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"osGroupPrivilege",key);
        },
        init(id, isTab) {
            //获取传入的租户。
            if (!id && this.$route.params.tenantId && !isTab) {
                this.tenantId = this.$route.params.tenantId;
            } else {
                this.tenantId = id;
            }
            let self = this;
            OsDimensionApi.getDimList(this.tenantId).then(res => {
                const data = res.data.filter(item=>{
                    return item.isGrant=="YES";
                })
                self.dimTree = []
                self.buildTree(data, self.dimTree, 0)
                //保存最初的维度信息
                self.originDimTree = self.dimTree;
                self.expandedKeys = data.map(m => m.parentId)
            })
        },
        setParam(){
            this.queryParam.Q_APP_ID__S_EQ=this.appId;
            if(this.groupId){
                this.queryParam.Q_GROUP_ID__S_EQ=this.groupId;
                this.getListByParams();
            }else {
                this.queryParam.Q_DIM_ID__S_EQ="1";
            }
        },
        delById(id) {
            var self=this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                zIndex: 20000,
                content: this.i18n('tipsDialog.content','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.okBtn','确定'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    OsGroupPrivilegeApi.del({ids: id}).then(res=>{
                        if(!res || !res.success){
                            return;
                        }
                        if(self.groupId){
                            self.loadData();
                        }else {
                            self.$refs.table.loadData();
                        }
                    });
                }
            })
        },
        getListByParams(newData) {
            var parameter={"pageNo":1,"pageSize":10,"sortField":"","sortOrder":"asc","params":this.queryParam};
            OsGroupPrivilegeApi.query(parameter).then(res=>{
                if(res.data){
                    var data=res.data;
                    if(newData && newData.length>0){
                        data.push(...newData);
                    }
                    this.dataSource=data;
                }
            });
        },
        save(record,index){
            OsGroupPrivilegeApi.save(record).then(res=>{
                if(!res || !res.success){
                    return;
                }
                if(!record.id){
                    this.dataSource.splice(index,1);
                }
                this.loadData();
            });
        },
        del(record,index){
            if(record.pkId){
                this.delById(record.pkId);
            }else {
                this.dataSource.splice(index,1);
            }
        },
        loadData(){
            var newData=[];
            for (let i = 0; i < this.dataSource.length; i++) {
                if(this.dataSource[i].isNew){
                    newData.push(this.dataSource[i]);
                }
            }
            this.getListByParams(newData);
        },
        addPrivilege(){
            //资源授权新增
            if(!this.groupId){
                var self=this;
                let conf = {
                    curVm: this,
                    max:true,
                    component: OsGroupGrant,
                    title: this.i18n('list.groupPrivilege','资源授权'),
                    cancel:function (){
                        self.$refs.table.loadData();
                    }
                };
                Util.open(conf, function (action) {
                });
                return;
            }
            if(this.dataSource.length>=2){
                this.$message.warning(this.i18n('tipsDialog.warning','只允许有包含与不包含两条数据'));
                return;
            }
            this.dataSource.push({
                serial:this.dataSource.length+1,
                groupId:this.groupId,
                groupName:this.groupName,
                dimId:this.dimId,
                containSub:"YES",
                appId:this.appId,
                isNew:true
            });
        },
        //授权菜单
        assignMenu(record) {
            let params = {
                pkId: record?record.groupId : this.groupId,
                dimId:record?record.dimId : this.dimId,
                containSub:record.containSub
            };
            if(record){
                params.privilegeId = record.id;
            }
            // 获取当前应用
            let appId = this.curApp.appId;
            if (appId) {
                params.appId = appId;
            }
            let conf = {
                curVm: this,
                data: params,
                widthHeight: ['900px', '600px'],
                component: OsGroupMenuEdit2,
                title: this.groupName||record.groupName  + this.i18n('list.menuAuthorization','菜单授权')
            };
            Util.open(conf, function (action) {
            });
        },
        handleDimSelectRxVueTree(tree,parenData,active){
            if (this.selectedKeys && this.selectedKeys.length > 0) {
                this.queryParam.Q_DIM_ID__S_EQ = this.selectedKeys[0];
                if(this.groupId){
                    this.loadData();
                }else {
                    this.$refs.table.loadData();
                }
            }
        },
        search(){
            if(this.groupId){
                this.loadData();
            }else {
                this.$refs.table.loadData();
            }
        },
        cancel() {
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        handleChange(e) {
            this.searchDept()
        },
        searchDept() {
            const value = this.searchValue
            if (!value){
                this.dimTree = this.originDimTree
            }else {
                this.dimTree = this.originDimTree.filter(item => (item.title.indexOf(value) > -1))
            }
        },
        emitEmpty() {
            this.$refs.searchInput.focus()
            this.searchValue = ''
            this.searchDept()
        },
        buildTree(list, arr, parentId) {
            list.forEach(item => {
                if (item.parentId === parentId) {
                    var child = {
                        key: item.dimId,
                        value: item.dimId, // value是给modal的select用的，2者属性不一样
                        title: item.name,
                        isGrant: item.isGrant,
                        showType: item.showType,
                        scopedSlots: {title: 'title'},
                        children: []
                    }
                    this.buildTree(list, child.children, item.dimId)
                    if (child.children.length === 0) {
                        delete child.children
                    }
                    arr.push(child)
                }
            })
        },
    },
    watch: {
        '$route': {
            handler: function (val) {
                if (!this.groupId) {
                    this.$refs.table.loadData()
                }
            },
            deep: true
        }
    }
}
</script>
<style scoped>

</style>

